package com.weiyan.predicates;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author misterWei
 * @create 2020年02月27号:15点44分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 自定义配置断言
 */
@Component
public class SexRoutePredicateFactory extends AbstractRoutePredicateFactory<SexRoutePredicateFactory.Config> {

    public SexRoutePredicateFactory(){
        super(SexRoutePredicateFactory.Config.class);
    }

    /**
     * 从配置文件中读取配值
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //这里的顺序要跟配置文件中的参数顺序一致
        return Arrays.asList("sex");
    }


    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return (serverWebExchange)->{
            String sex = serverWebExchange.getRequest().getQueryParams().getFirst("sex");
            if (StringUtils.isNotEmpty(sex)) {

                if (StringUtils.equals(sex,config.getSex())) {
                    return true;
                }else {
                    return false;
                }

            }

            return false;
        };
    }





    //必须是静态类
    @Data
    @NoArgsConstructor
    public static class Config {
        private String sex;

    }
}
